﻿Imports System
Imports System.Collections.Generic
Imports System.Windows.Browser

Namespace Utilities

    Public Class ClientAPI
        '//define delegate event signature that matches javascript
        Public Delegate Sub ControlMethodDelegate(ByVal payload As Object, ByVal context As Object, ByVal request As Object)

        Private Shared _xmlhttp As ScriptObject
        Public Shared Sub InvokeControlMethod(ByVal callbackID As String, ByVal method As String, ByVal arguments As IDictionary(Of String, Object), ByVal successFunc As ControlMethodDelegate, ByVal failFunc As ControlMethodDelegate)
            '//get a reference to javascript dnn.xmlhttp object
            If _xmlhttp Is Nothing Then
                _xmlhttp = CType(HtmlPage.Window.Eval("dnn.xmlhttp"), ScriptObject)
            End If
            _xmlhttp.Invoke("callControlMethod", callbackID, method, DictionaryToScriptObject(arguments), successFunc, failFunc)
        End Sub

        Private Shared Function DictionaryToScriptObject(ByVal dict As IDictionary(Of String, Object)) As ScriptObject
            If dict Is Nothing Then
                Return Nothing
            End If

            Dim obj As ScriptObject = HtmlPage.Window.CreateInstance("Object")
            Dim key As String

            For Each key In dict.Keys
                obj.SetProperty(key, dict(key))
            Next
            Return obj
        End Function

    End Class
End Namespace